package com.manager.enterprise.module.service;

import com.manager.commons.Constant;
import com.manager.commons.base.DataGrid;
import com.manager.commons.mybatis.dao.GenericDao;
import com.manager.commons.mybatis.service.GenericService;
import com.manager.commons.utils.PinyinUtil;
import com.manager.commons.utils.StringUtil;
import com.manager.commons.utils.UUIDUtil;
import com.manager.core.module.manager.entity.ComboTreeList;
import com.manager.core.web.json.AjaxJson;
import com.manager.enterprise.module.dao.GenFilesDao;
import com.manager.enterprise.module.dao.GenOrganizationDao;
import com.manager.enterprise.module.entity.GenFiles;
import com.manager.enterprise.module.entity.GenOrganization;
import com.manager.enterprise.utils.CodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * GenOrganizationService
 * 组织架构
 *
 * @author manager
 * @version 1.0
 */
@Service
public class GenOrganizationService extends GenericService<GenOrganization> {

    @Autowired
    private GenOrganizationDao jdbcDao;
    @Autowired
    private GenFilesDao filesDao;

    @Override
    public GenericDao<GenOrganization> getDao() {
        return jdbcDao;
    }

    public GenOrganization findOne(Map<String, Object> params) {
        return jdbcDao.findOne(params);
    }

    /**
     * 保存
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson mySave(Map<String, Object> params) throws Exception {
        String msg = "请求错误，请稍后再试！";
        if (null != params) {
            String _id = String.valueOf(params.get("_id"));
            String parent_code = getParamsString(params, "parent_code");
            String name = getParamsString(params, "name");
            if (StringUtil.isNotEmpty(name)) {
                Integer n = jdbcDao.findModelName(params);
                if (n == null || n == 0) {
                    String code = PinyinUtil.getFirstLetter(name);
                    code = CodeGenerator.generateOrderNumber(code);
                    params.put("code", code);
                    GenFiles genFiles = new GenFiles();
                    genFiles.setName(name);
                    genFiles.setCreator(getParamsString(params, "creator"));
                    GenOrganization organization = null;
                    if (StringUtil.isEmpty(parent_code)) {
                        params.put("level", 1);
                        params.put("levelCode", code);
                        genFiles.setPath("/" + getCreator(params));
                    } else {
                        params.put("parentId", parent_code);
                        genFiles.setPid(parent_code);
                        organization = jdbcDao.findModelPath(parent_code);
                        if (organization != null && StringUtil.isNotEmpty(organization.getLevelCode())) {
                            params.put("levelCode", organization.getLevelCode() + "-" + code);
                            params.put("level", organization.getLevel() + 1);
                        }
                        if (organization != null) {
                            genFiles.setPath(organization.getPath() + "/" + organization.getName());
                        }
                    }
                    int f = 0;
                    if (StringUtil.isEmpty(_id)) {
                        String uuid = UUIDUtil.getInstance().getUUID();
                        params.put("id", uuid);
                        f = insertMap(params);
                        genFiles.setId(uuid);
                        genFiles.setGoId(uuid);
                        genFiles.setType(Constant.FileType.FOLDER.getEcode());
                        if (organization != null) {
                            genFiles.setLevelId(organization.getLevelId() + "-" + uuid);
                        } else {
                            genFiles.setLevelId(uuid);
                        }
                        f += filesDao.insert(genFiles);
                    } else {
                        params.put("id", _id);
                        f = updateMap(params);
                        genFiles.setId(_id);
                        genFiles.setGoId(_id);
                        if (organization != null) {
                            genFiles.setLevelId(organization.getLevelId() + "-" + _id);
                        } else {
                            genFiles.setLevelId(_id);
                        }
                        f += filesDao.update(genFiles);
                    }
                    if (f == 2) {
                        return new AjaxJson(1, "保存成功");
                    } else {
                        throw new Exception("数据保存异常，请稍后再试！");
                    }
                } else {
                    msg = "名称重复，请从新输入！";
                }
            } else {
                msg = "请输入名称";
            }

        }
        return new AjaxJson(msg);
    }

    /**
     * 改变状态
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson myStatus(Map<String, Object> params) throws Exception {
        if (null != params) {
            int f = statusMap(params);
            f += filesDao.statusMap(params);
            if (f == 2) {
                return new AjaxJson(1, "操作成功");
            } else {
                throw new Exception("数据保存异常，请稍后再试！");
            }
        }
        return new AjaxJson("参数错误！");


    }

    /**
     * 删除
     *
     * @param params
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public AjaxJson myDelete(Map<String, Object> params) throws Exception {
        if (null != params) {
            int f = destroyMap(params);
            f += filesDao.destroyMap(params);
            if (f == 2) {
                return new AjaxJson(1, "操作成功");
            } else {
                throw new Exception("数据保存异常，请稍后再试！");
            }
        }
        return new AjaxJson("参数错误");

    }

    /**
     * 分页查询
     *
     * @param params
     * @return
     */
    public DataGrid queryPage(Map<String, Object> params) {
        try {
            if (null != params) {
                int count = jdbcDao.countMap(params);
                List<GenOrganization> list = jdbcDao.queryMap(params);
                queryChildren(list, params);
                return new DataGrid(count, list);
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return new DataGrid(0, new ArrayList<GenOrganization>());
    }

    private void queryChildren(List<GenOrganization> list, Map<String, Object> params) {
        for (GenOrganization gtc : list) {
            params.put("parent_code", gtc.getId());
            List<GenOrganization> l = jdbcDao.queryMap(params);
            if (l != null && !l.isEmpty()) {
                gtc.setChildren(l);
                queryChildren(l, params);
            }
        }
    }

    public List<ComboTreeList> queryTreeList(Map<String, Object> params) {
        return jdbcDao.queryTree(params);
    }
}
